﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace PmSoft.Core.Extensions;

/// <summary>
/// 表示 ISession 的扩展方法
/// </summary>
public static class SessionExtensions
{
	/// <summary>
	/// 将值设置到 Session 中
	/// </summary>
	/// <typeparam name="T">值的类型</typeparam>
	/// <param name="session">Session</param>
	/// <param name="key">键</param>
	/// <param name="value">值</param>
	/// <returns>表示异步操作的任务</returns>
	public static async Task SetAsync<T>(this ISession session, string key, T value)
	{
		await LoadAsync(session);
		session.SetString(key, JsonConvert.SerializeObject(value));
	}

	/// <summary>
	/// 从 Session 中获取值
	/// </summary>
	/// <typeparam name="T">值的类型</typeparam>
	/// <param name="session">Session</param>
	/// <param name="key">键</param>
	/// <returns>表示异步操作的任务，任务结果包含值</returns>
	public static async Task<T?> GetAsync<T>(this ISession session, string key)
	{
		await LoadAsync(session);
		var value = session.GetString(key);
		return value == null ? default : JsonConvert.DeserializeObject<T>(value);
	}

	/// <summary>
	/// 如果存在，从 Session 中移除给定的键
	/// </summary>
	/// <param name="session">Session</param>
	/// <param name="key">键</param>
	/// <returns>表示异步操作的任务</returns>
	public static async Task RemoveAsync(this ISession session, string key)
	{
		await LoadAsync(session);
		session.Remove(key);
	}

	/// <summary>
	/// 移除当前 Session 中的所有条目（如果有）。Session cookie 不会被移除。
	/// </summary>
	/// <param name="session">Session</param>
	/// <returns>表示异步操作的任务</returns>
	public static async Task ClearAsync(this ISession session)
	{
		await LoadAsync(session);
		session.Clear();
	}

	/// <summary>
	/// 尝试从数据存储中异步加载 Session
	/// </summary>
	/// <param name="session">Session</param>
	/// <returns>表示异步操作的任务</returns>
	public static async Task LoadAsync(ISession session)
	{
		try
		{
			await session.LoadAsync();
		}
		catch
		{
			// 回退到同步处理
		}
	}
}
